import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:im_flutter_sdk_example/utils/theme_util.dart';

import 'package:im_flutter_sdk_example/utils/style.dart';
import 'package:im_flutter_sdk_example/utils/localizations.dart';
import 'package:im_flutter_sdk_example/common/common.dart';
import 'package:im_flutter_sdk_example/pages/chat_page.dart';
import 'package:im_flutter_sdk_example/utils/widget_util.dart';

class EMContactsListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _EMContactsListPageState();
  }
}

class _EMContactsListPageState extends State<EMContactsListPage>
    implements EMContactEventListener {
  int contactItemCount = 1;
  String _imageName;
  String _name;

  List<EMContact> contactsList = new List();

  var imageNameList = [];

  Offset tapPos;

  @override
  void initState() {
    super.initState();
    EMClient.getInstance.contactManager.addContactListener(this);
    loadEMContactsList();
  }

  @override
  void dispose() {
    super.dispose();
    EMClient.getInstance.contactManager.removeContactListener(this);
  }

  EMContact _getData(int index) {
    return this.contactsList[index];
  }

  @override
  Widget build(BuildContext context) {
    // 允许子控件滑动
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(DemoLocalizations.of(context).addressBook,
            style: TextStyle(
                fontSize: EMFont.emAppBarTitleFont,
                color: ThemeUtils.isDark(context)
                    ? EMColor.darkText
                    : EMColor.text)),
        leading: Builder(builder: (BuildContext context) {
          return IconButton(
              icon: new Icon(Icons.arrow_back, color: Colors.black),
              onPressed: () {
                Navigator.pop(context, true);
              });
        }),
        elevation: 0, // 隐藏阴影
        backgroundColor:
            ThemeUtils.isDark(context) ? EMColor.darkAppMain : EMColor.appMain,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.add, color: Colors.black),
              onPressed: () {
                Navigator.of(context).pushNamed(Constant.toAddContact);
              }),
          SizedBox(width: 12.0),
        ],
      ),
      key: UniqueKey(),
      body: ListView.builder(
//        shrinkWrap: true,
//        physics:NeverScrollableScrollPhysics(),
        itemCount: this.contactsList.length,
        itemBuilder: (BuildContext context, int index) {
          return _rowStyle(index);
        },
      ),
    );
  }

  Widget _rowStyle(int index) {
    this._imageName = 'images/default_avatar.png';
    this._name = _getData(index).markName;
    return InkWell(
      onTap: () {
        print('object : ${_getData(index)}');
        _pushToChatPage(_getData(index).eid);
      },
      onTapDown: (TapDownDetails details) {
        tapPos = details.globalPosition;
      },
      onLongPress: () {
        if (index >= 7) {
          Map<String, String> actionMap = {
            Constant.deleteContactKey:
                DemoLocalizations.of(context).deleteContact,
          };
          WidgetUtil.showLongPressMenu(context, tapPos, actionMap,
              (String key) {
            if (key == "DeleteContactKey") {
              _deleteContact(index);
            }
          });
        }
      },
      child: Stack(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(left: 16.0),
            height: EMLayout.emContactListItemHeight,
            child: Row(
              children: <Widget>[
                ClipOval(
                  child: Image.asset(
                    this._imageName,
                    width: EMLayout.emContactListPortraitSize,
                    height: EMLayout.emContactListPortraitSize,
                  ),
                ),
                Padding(padding: EdgeInsets.all(8.0)),
                Text(
                  this._name,
                  style: TextStyle(fontSize: 18.0),
                )
              ],
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width - 64.0,
            height: 1.0,
            color: Color(0xffe5e5e5),
            margin: EdgeInsets.fromLTRB(64.0, 66.0, 0.0, 0.0),
          ),
        ],
      ),
    );
  }

  void _pushToChatPage(String chatter,
      [EMConversationType type = EMConversationType.Chat]) async {
    try {
      print('chatter: ${chatter.toString()}');
      // 查询 当前聊天对象信息
      EMContact contact;
      this.contactsList.forEach((element) {
        if (element.eid == chatter) {
          contact = element;
        }
      });
      EMConversation conversation =
          await EMClient.getInstance.chatManager.getConversation(chatter, type);
      if (contact != null) {
        conversation.ext = {"nickname": contact.nickname};
      }
      Navigator.push(context,
          new MaterialPageRoute(builder: (BuildContext context) {
        return new ChatPage(conversation: conversation);
      }));
    } catch (e) {
      print('create conversation error');
    }
  }

  void loadEMContactsList() async {
    try {
      this.contactsList =
          await EMClient.getInstance.contactManager.getAllContactsFromServer();
      print(
        'load contacts list ${this.contactsList}',
      );
      _refreshUI();
    } catch (e) {
      WidgetUtil.hintBoxWithDefault(e.toString());
    }
    // im/friend_list
  }

  void _refreshUI() {
    setState(() {});
  }

  _deleteContact(int index) async {
    try {
      EMClient.getInstance.contactManager
          .deleteContact(username: _getData(index - contactItemCount).eid);
      this.contactsList.removeAt(index - contactItemCount);
      loadEMContactsList();
    } catch (e) {}
  }

  void onContactAdded(String userName) {
    loadEMContactsList();
  }

  void onContactDeleted(String userName) {
    loadEMContactsList();
  }

  void onContactInvited(String userName, String reason) async {
    try {
      EMClient.getInstance.contactManager.acceptInvitation(username: userName);
      WidgetUtil.hintBoxWithDefault('自动同意$userName的好友请求!');
    } catch (e) {
      WidgetUtil.hintBoxWithDefault(e.toString());
    } finally {
      loadEMContactsList();
    }
  }

  void onFriendRequestAccepted(String userName) {
    loadEMContactsList();
  }

  void onFriendRequestDeclined(String userName) {
    loadEMContactsList();
  }
}
